package com.culture.config.wrapper;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.culture.config.dao.entity.User;
import com.culture.config.dao.entity.UserAction;
import com.culture.config.dao.entity.UserRole;
import com.culture.config.model.ActionAuthority;
import com.culture.config.model.AuthInfo;
import com.culture.config.model.RoleGrantedAuthority;

import lombok.experimental.UtilityClass;

@UtilityClass
public class AuthWrapper {
	
	public static UserDetails wrapUserDetails(User user, List<UserRole> userRoleList,List<UserAction> userRoleActionList) {
		UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUserName(), 
				user.getUserPassword(),
				user.getEnable(),
				true,
				true,
				true,
				getAuthorities(userRoleList,userRoleActionList));
		return userDetails;
	}
	
	public static Collection<GrantedAuthority> getAuthorities(List<UserRole> userRoleList,List<UserAction> userRoleActionList){   		
		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
		//role list
		if(CollectionUtils.isNotEmpty(userRoleList)) {			
			userRoleList.forEach(e->authList.add(new RoleGrantedAuthority(e)));	 
		}	
		//role action list
		if(CollectionUtils.isNotEmpty(userRoleActionList)) {
			userRoleActionList.forEach(e->authList.add(new ActionAuthority(e)));
		}	
		return authList;    
	}	
	
	public static AuthInfo wrapAuthInfo(User user,List<UserRole> userRoleList) {
		AuthInfo authInfo = new AuthInfo(user.getId(),user.getUserName());
		if(CollectionUtils.isNotEmpty(userRoleList)) {
			authInfo.setRoles(userRoleList.stream().map(UserRole::getRoleName).collect(Collectors.toList()));
		}
		return authInfo;
	}
	
}
